import common from '../../../lib/common/common.js'
import {
    getPlayerData,
    getPlayerList,
    getStolenVegetableData,
    isPlayerExist,
    storagePlayerData,
    storeStolenVegetableData,
    timestampToSeconds
} from '../l.js'
import lodash from 'lodash'

export class Fs extends plugin {
    constructor() {
        super({
            name: '[Fs]偷菜',
            dsc: '偷菜',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^(#|\/)?偷菜列表$/, fnc: 'listOfStolenVegetables' },
                { reg: /^偷菜(\d+)/, fnc: 'stealingVegetables' },
                { reg: /^(偷菜|被偷)日志$/, fnc: 'stealingVegetableLogs' }
            ]
        })
        this.task = {
            name: '[Fs]重置偷菜次数',
            fnc: () => this.resetTimes(),
            cron: '1 0 0 * * *'
        }
    }

    async listOfStolenVegetables(e) {
        const playerID = e.user_id
        if (!isPlayerExist(playerID)) {
            return e.reply(['无玩家信息，请发送[领取田地]'])
        }

        const playerFileList = (getPlayerList()).filter(item => item !== playerID + '.json')

        let canStealList = []
        for (const playerFile of playerFileList) {
            const playerID = playerFile.replace(/.json/g, '')
            const playerData = await getPlayerData(playerID)

            for (const frame of playerData['frame']) {
                if (frame['start']) {
                    if (frame['time'] - timestampToSeconds(Date.now()) < 0) {
                        frame['ID'] = playerID
                        canStealList.push(frame)
                    }
                }
            }
        }

        for (let i = 0; i < canStealList.length; i++) {
            canStealList[i]['index'] = i
        }

        storeStolenVegetableData(canStealList)

        if (canStealList.length === 0) {
            return e.reply(['没有菜可以偷'])
        }

        let msg = ['请发送[偷菜+序号]来偷菜，如[偷菜1]']
        for (let i = 0; i < canStealList.length; i++) {
            const { name, ID, index } = canStealList[i]
            msg.push(`序号: ${index}\r作物: ${name}\r拥有者: ${ID}`)
        }

        return e.reply(await common.makeForwardMsg(e, msg, '点击查看可偷列表'))
    }

    async stealingVegetables(e) {
        const playerID = e.user_id
        if (!isPlayerExist(playerID)) {
            return e.reply(['无玩家信息，请发送[领取田地]'])
        }

        const [, index] = e.msg.match(/^偷菜(\d+)/)

        const stolenVegetableData = await getStolenVegetableData()
        const { name, ID, number } = stolenVegetableData[index]

        const playerData = await getPlayerData(playerID)
        const stolenPlayerData = await getPlayerData(ID)

        if (playerData['numberOfVegetableThefts'] === 'GG') {
            return e.reply(['你被抓起来了，今天不能偷菜了'])
        } else if (playerData['numberOfVegetableThefts'] >= 5) {
            return e.reply(['每天只能偷五次，今日已上限'])
        }

        const randomNumber = lodash.random(1, 10000)
        if (randomNumber > 1000 && randomNumber < 2000) {
            playerData['numberOfVegetableThefts'] = 'GG'
            storagePlayerData(playerID, playerData)

            return e.reply(['偷取失败，被发现并抓起来了，今天不能偷菜啦'])
        }

        if (!playerData['Stash'][name]) {
            playerData['Stash'][name] = { number: 0 }
        }
        if (!playerData['numberOfVegetableThefts']) {
            playerData['numberOfVegetableThefts'] = 0
        }

        playerData['Stash'][name]['number'] += number
        playerData['numberOfVegetableThefts'] += 1
        storagePlayerData(playerID, playerData)

        let found = false;
        stolenPlayerData['frame'].forEach(obj => {
            if (obj['time'] - timestampToSeconds(Date.now()) < 0) {
                if (obj['name'] === name && !found) {
                    obj['start'] = false
                    found = true
                }
            }
        });
        if (!stolenPlayerData['stealingVegetableLogs']) {
            stolenPlayerData['stealingVegetableLogs'] = []
        }
        stolenPlayerData['stealingVegetableLogs'].push(`[${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}] 被${playerID}偷了${name}`)
        storagePlayerData(ID, stolenPlayerData)

        const msg = [
            '成功啦~',
            `成功偷到[${number}]个[${name}]`
        ]
        await this.listOfStolenVegetables(e)
        return e.reply(msg.join('\r'))
    }

    async stealingVegetableLogs(e) {
        const playerID = e.user_id
        if (!isPlayerExist(playerID)) {
            return e.reply(['无玩家信息，请发送[领取田地]'])
        }

        const playerData = await getPlayerData(playerID)

        if (!playerData['stealingVegetableLogs']) {
            playerData['stealingVegetableLogs'] = []
        }

        if (playerData['stealingVegetableLogs'].length === 0) {
            return e.reply(['还没被偷过菜'])
        }

        return e.reply(await common.makeForwardMsg(e, playerData['stealingVegetableLogs'], '被偷日志'))
    }

    async resetTimes() {
        const playerFileList = getPlayerList()
        for (const playerFile of playerFileList) {
            const playerID = playerFile.replace(/.json/g, '')
            const playerData = await getPlayerData(playerID)

            playerData['numberOfVegetableThefts'] = 0
            storagePlayerData(playerID, playerData)
        }
    }
}